﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IsreversI.GameLogic
{
    /// <summary>
    /// Base class for all views and controllers.
    /// </summary>
    class BoardModelAttachment
    {
        #region member variables
        /// <summary>
        /// Handler for events related to the game board.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="bea">Extra information about the event.</param>
        public delegate void BoardEventHandler(object sender, BoardEventArgs bea);

        private BoardModel model;
        #endregion

        #region events
        /// <summary>
        /// Triggered before the current object is updated.
        /// </summary>
        public event BoardEventHandler PreBoardModelChanged;

        /// <summary>
        /// Triggered after the current object is updated.
        /// </summary>
        public event BoardEventHandler PostBoardModelChanged;
        #endregion

        #region properties
        /// <summary>
        /// Model this view or controller is currently working with.
        /// </summary>
        /// <remarks>
        /// During a model change operation, this property has the value of the *NEW* model.
        /// </remarks>
        public BoardModel BoardModel
        {
            get
            {
                return this.model;
            }
            set
            {
                // Prevent model being swapped twice.
                if (this.model != value)
                {
                    this.model = value;
                    if (PreBoardModelChanged != null)
                        PreBoardModelChanged(this, new BoardEventArgs(value));
                    this.handleModelChange(value);
                    if (PostBoardModelChanged != null)
                        PostBoardModelChanged(this, new BoardEventArgs(value));
                }
            }
        }
        #endregion

        #region event handlers
        /// <summary>
        /// Public event handler designed to allow objects to force other objects to
        /// respond to changes of model.
        /// </summary>
        public void acceptNewModel(object sender, BoardEventArgs bea)
        {
            this.BoardModel = bea.BoardModel;
        }
        #endregion

        #region protected methods
        /// <summary>
        /// Handler run when the model is changed.  The base implementation should
        /// be used in order to set the model of the object without triggering events.
        /// </summary>
        protected virtual void handleModelChange(BoardModel model)
        {
            // Kept to allow quiet setting of model in derived functions.
            this.model = model;
        }
        #endregion
    }
}
